package com.dgt.trade.controller;

import com.alibaba.fastjson.JSON;
import com.dgt.trade.entitys.User;
import com.dgt.trade.entitys.UserBalance;
import com.dgt.trade.entitys.yifu.*;
import com.dgt.trade.service.BankCardService;
import com.dgt.trade.service.IUserService;
import com.dgt.trade.service.UserBalanceService;
import com.dgt.trade.utils.ConstantsUtils;
import com.dgt.trade.utils.HttpClientUtil;
import com.dgt.trade.utils.MD5Util;
import com.dgt.trade.utils.MapToStringSplicing;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 出金
 */
@Controller
@RequestMapping("/put")
public class PutController extends BaseController {

    @Autowired
    private BankCardService bankCardService;

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private IUserService iUserService;

    /**
     * 提交出金申请:
     * 步骤1：根据API获取子账户的可出资金和保证金判断用户能否出金。
     * 步骤2：根据API获取子账户绑定的银行卡等信息。
     * 步骤3：调用出金申请接口，出金申请接口会将子账户的资金减掉。
     * 步骤4：出金申请返回成功后可在管理端 => 子账户财务审核处理。
     *
     * @return
     */

    @RequestMapping("/index")
    public ModelAndView Out_of_gold(String mobile, String money) {
        ModelAndView view = new ModelAndView();
        User sUser = getUser(request);
        String time = String.valueOf(new Date().getTime());
        Integer status = null;
        String message = null;
        String SubAccountID = sUser.getSubAccountID();
        String AvailableFund = null;
        String MarginFund = null;
        String BaseCurrency = null;
        String ExecRate = null;
        String BankName = null;
        String Name = null;
        String BankAccount = null;
        String WithdrawAmount = null;
        String RequestSequenceNo = null;

        //步骤1：根据API获取子账户的可出资金和保证金判断用户能否出金。

        Map<String, String> select_money = new LinkedHashMap<String, String>();
        Subaccounts_fund subaccounts_fund = new Subaccounts_fund();
        subaccounts_fund.setSubAccountID(SubAccountID);
        subaccounts_fund.setCurrency(YF_Currency.CURRENCY_CNY);
        subaccounts_fund.setTimeStamp(time);
        subaccounts_fund.setVersion("1.0");
        String str = MD5Util.MD5_money(subaccounts_fund.getSubAccountID(), subaccounts_fund.getCurrency(), subaccounts_fund.getTimeStamp(), subaccounts_fund.getVersion());
        subaccounts_fund.setSignMsg(str);

        select_money.put("SubAccountID", subaccounts_fund.getSubAccountID());
        select_money.put("Currency", subaccounts_fund.getCurrency());
        select_money.put("TimeStamp", subaccounts_fund.getTimeStamp());
        select_money.put("Version", subaccounts_fund.getVersion());
        select_money.put("SignMsg", subaccounts_fund.getSignMsg());

        String query1 = MapToStringSplicing.createLinkStringByGet(select_money);

        String result = null;
        try {
            result = HttpClientUtil.getProcessDefinitionList("http://120.55.162.84:8050/api/subaccounts/fund?" + query1, select_money);
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result);
            JsonArray array = null;
            JsonObject subObject = null;
            status = object.get("status").getAsInt();
            if (status == 0) {
                array = object.get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    subObject = array.get(i).getAsJsonObject();
                    AvailableFund = subObject.get("AvailableFund").getAsString();//可出资金(单位:基础币种)
                    MarginFund = subObject.get("MarginFund").getAsString();//占用保证金(单位:子账户的基础币种)
                    BaseCurrency = subObject.get("BaseCurrency").getAsString();//	子账户的基础币种
                    ExecRate = subObject.get("ExecRate").getAsString();//	执行汇率
                }
            } else {
                message = object.get("message").getAsString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (status == 0) {
            System.out.println("查询成功！");
        } else {
            System.out.println("查询失败！");
        }

        //步骤2：根据API获取子账户绑定的银行卡等信息。

        Map<String, String> select_bank = new LinkedHashMap<String, String>();
        Subaccounts_banks subaccounts_banks = new Subaccounts_banks();
        subaccounts_banks.setSubAccountID(SubAccountID);
        subaccounts_banks.setTimeStamp(time);
        subaccounts_banks.setVersion("1.0");
        String msg = MD5Util.MD5_bank(subaccounts_banks.getSubAccountID(), subaccounts_banks.getTimeStamp(), subaccounts_banks.getVersion());
        subaccounts_banks.setSignMsg(msg);

        select_bank.put("SubAccountID", subaccounts_banks.getSubAccountID());
        select_bank.put("TimeStamp", subaccounts_banks.getTimeStamp());
        select_bank.put("Version", subaccounts_banks.getVersion());
        select_bank.put("SignMsg", subaccounts_banks.getSignMsg());

        String query2 = MapToStringSplicing.createLinkStringByGet(select_bank);

        String result1 = null;
        try {
            result1 = HttpClientUtil.getProcessDefinitionList("http://120.55.162.84:8050/api/subaccounts/banks?" + query2, select_bank);
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result1);
            JsonArray array = null;
            JsonObject subObject = null;
            status = object.get("status").getAsInt();
            if (status == 0) {
                array = object.get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    subObject = array.get(i).getAsJsonObject();
                    BankName = subObject.get("BankName").getAsString();//	银行名称
                    Name = subObject.get("Name").getAsString();//	姓名
                    BankAccount = subObject.get("BankAccount").getAsString();//	银行卡号
                }
            } else {
                message = object.get("message").getAsString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (status == 0) {
            System.out.println("查询绑定银行卡列表成功！");
        } else {
            System.out.println("查询绑定银行卡列表失败！");
        }

        //步骤3：调用出金申请接口，出金申请接口会将子账户的资金减掉。

        Map<String, String> apply_for = new LinkedHashMap<String, String>();
        Subtransferaudits subtransferaudits = new Subtransferaudits();
        subtransferaudits.setBankName(BankName);
        subtransferaudits.setName(Name);
        subtransferaudits.setBankAccount(BankAccount);
        subtransferaudits.setSubAccountID(SubAccountID);
        subtransferaudits.setAmount(money);

        //子账户有保证金的时候，不允许出金
        if (!MarginFund.equals("0")) {
            subtransferaudits.setPosition("false");
        } else {
            subtransferaudits.setPosition("true");
        }

        subtransferaudits.setTimeStamp(time);
        subtransferaudits.setVersion("1.0");
        String msg1 = MD5Util.MD5_subtransferaudits(subtransferaudits.getBankName(), subtransferaudits.getName(), subtransferaudits.getBankAccount(), subtransferaudits.getSubAccountID(), subtransferaudits.getAmount(), subtransferaudits.getPosition(), subtransferaudits.getTimeStamp(), subtransferaudits.getVersion());
        subtransferaudits.setSignMsg(msg1);

        apply_for.put("BankName", subtransferaudits.getBankName());
        apply_for.put("Name", subtransferaudits.getName());
        apply_for.put("BankAccount", subtransferaudits.getBankAccount());
        apply_for.put("SubAccountID", subtransferaudits.getSubAccountID());
        apply_for.put("Amount", subtransferaudits.getAmount());
        apply_for.put("Position", subtransferaudits.getPosition());
        apply_for.put("TimeStamp", subtransferaudits.getTimeStamp());
        apply_for.put("Version", subtransferaudits.getVersion());
        apply_for.put("SignMsg", subtransferaudits.getSignMsg());

        String query3 = MapToStringSplicing.createLinkStringByGet(apply_for);

        String result2 = null;
        try {
            result2 = HttpClientUtil.putProcessRuntimeTask("http://120.55.162.84:8050/api/subtransferaudits?" + query3, apply_for);
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result2);
            JsonArray array = null;
            JsonObject subObject = null;
            status = object.get("status").getAsInt();
            if (status == 0 || status == 2003 || status == 2004) {
                array = object.get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    subObject = array.get(i).getAsJsonObject();
                    WithdrawAmount = subObject.get("WithdrawAmount").getAsString();//	到账金额。(参数金额*人民币对基础币种汇率)
                    AvailableFund = subObject.get("AvailableFund").getAsString();//剩余可出资金(单位:基础币种)
                    MarginFund = subObject.get("MarginFund").getAsString();//占用保证金(单位:子账户的基础币种)
                    BaseCurrency = subObject.get("BaseCurrency").getAsString();//子账户的基础币种
                    ExecRate = subObject.get("ExecRate").getAsString();//执行汇率
                    RequestSequenceNo = subObject.get("RequestSequenceNo").getAsString();//流水号
                }
            } else {
                message = object.get("message").getAsString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (status == 0) {
            System.out.println("出金申请提交成功！");
            UserBalance userBalance = new UserBalance();
            User user = getUser(request);
            userBalance.setUser_id(user.getId());
            userBalance.setData_type(2);
            Float balance = user.getBalance() - Integer.parseInt(money);
            userBalance.setBalance(balance);
            userBalance.setMoney(Float.parseFloat(money));
            userBalance.setData_status(2);
            userBalance.setData_desc("提现");
            int i = userBalanceService.insert(userBalance);
            boolean bool = iUserService.istixian(Float.valueOf(WithdrawAmount), user.getId());
            Map<String, String> map = new HashMap<String, String>();
            map.put("AvailableFund", AvailableFund);
            map.put("MarginFund", MarginFund);
            map.put("BaseCurrency", BaseCurrency);
            map.put("ExecRate", ExecRate);
            map.put("SubAccountID", SubAccountID);
            int j = bankCardService.updateBankCardById(map);
            request.getSession().removeAttribute(ConstantsUtils.LOGIN_KEY_FLAG);
            if (i > 0 && j > 0 && bool) {
                System.out.println("提现成功！");
                User user1 = iUserService.getMemberByMobile(mobile);
                user1.setPassword(null);
                request.getSession().setAttribute(ConstantsUtils.LOGIN_KEY_FLAG, JSON.toJSONString(user1));
                try {
                    response.sendRedirect("/user/index");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("提现失败！");
            }
        } else {
            System.out.println("出金申请提交失败！");
            view.setViewName("error/404");
        }
        view.setViewName("error/404");
        return view;
    }

    @RequestMapping("/bangding")
    public ModelAndView bangding(String bankName, String bankAccount) {
        String time = String.valueOf(new Date().getTime());
        Integer status = null;
        String message = null;
        String BankName = null;
        String Name = null;
        String BankAccount = null;

        ModelAndView view = new ModelAndView();

        User user = getUser(request);
        bangding_banks bangding = new bangding_banks();
        Map<String, String> bangdingMap = new LinkedHashMap<String, String>();

        bangding.setBankName(bankName);
        bangding.setName("a" + user.getMobile());
        bangding.setBankAccount(bankAccount);
        bangding.setSubAccountID(user.getSubAccountID());
        bangding.setTimeStamp(time);
        bangding.setVersion("1.0");
        String str = MD5Util.MD5_bangding(bangding.getBankName(), bangding.getName(), bangding.getBankAccount(), bangding.getSubAccountID(), bangding.getTimeStamp(), bangding.getVersion());
        bangding.setSignMsg(str);

        bangdingMap.put("BankName", bangding.getBankName());
        bangdingMap.put("Name", bangding.getName());
        bangdingMap.put("BankAccount", bangding.getBankAccount());
        bangdingMap.put("SubAccountID", bangding.getSubAccountID());
        bangdingMap.put("TimeStamp", bangding.getTimeStamp());
        bangdingMap.put("Version", bangding.getVersion());
        bangdingMap.put("SignMsg", bangding.getSignMsg());


        String query1 = MapToStringSplicing.createLinkStringByGet(bangdingMap);

        String result = null;
        try {
            result = HttpClientUtil.putProcessRuntimeTask("http://120.55.162.84:8050/api/subaccounts/banks?" + query1, bangdingMap);
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result);
            JsonArray array = null;
            JsonObject subObject = null;
            status = object.get("status").getAsInt();
            if (status == 0) {
                array = object.get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    subObject = array.get(i).getAsJsonObject();
                    BankName = subObject.get("BankName").getAsString();//	银行名称
                    Name = subObject.get("Name").getAsString();//	姓名
                    BankAccount = subObject.get("BankAccount").getAsString();//	银行卡号
                }
            } else {
                message = object.get("message").getAsString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (status == 0) {
            String id = String.valueOf(user.getId());
            Map<String, String> map = new HashMap<String, String>();
            map.put("user_id", id);
            map.put("BankName", BankName);
            map.put("Name", Name);
            map.put("BankAccount", BankAccount);
            int i = bankCardService.insertBankCardById(map);
            if (i > 0) {
                System.out.println("绑定银行卡成功！");
                try {
                    response.sendRedirect("/put/selectBankCardById");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("绑定银行卡失败！");
            }
        } else {
            System.out.println("【逸富】绑定银行卡失败！");
            view.setViewName("/error/404");
        }
        return view;

    }

    @RequestMapping("/jiebang")
    public ModelAndView jiebang(String bankAccount) {
        ModelAndView view = new ModelAndView();

        String time = String.valueOf(new Date().getTime());
        Integer status = null;
        String message = null;
        String BankName = null;
        String Name = null;
        String BankAccount = null;

        User user = getUser(request);
        jiebang_banks jiebangBanks = new jiebang_banks();
        jiebangBanks.setSubAccountID(user.getSubAccountID());
        jiebangBanks.setBankAccount(bankAccount.replace(" ", ""));
        jiebangBanks.setTimeStamp(time);
        jiebangBanks.setVersion("1.0");
        String str = MD5Util.MD5_jiebang(jiebangBanks.getBankAccount(), jiebangBanks.getSubAccountID(), jiebangBanks.getTimeStamp(), jiebangBanks.getVersion());
        jiebangBanks.setSignMsg(str);

        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("BankAccount", jiebangBanks.getBankAccount());
        map.put("SubAccountID", jiebangBanks.getSubAccountID());
        map.put("TimeStamp", jiebangBanks.getTimeStamp());
        map.put("Version", jiebangBanks.getVersion());
        map.put("SignMsg", jiebangBanks.getSignMsg());

        String query = MapToStringSplicing.createLinkStringByGet(map);

        try {
            String result = HttpClientUtil.deleteProcessRuntimeIdentityLink("http://120.55.162.84:8050/api/subaccounts/banks?" + query, map);
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result);
            JsonArray array = null;
            JsonObject subObject = null;
            status = object.get("status").getAsInt();
            if (status == 0) {
                array = object.get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    subObject = array.get(i).getAsJsonObject();
                    BankName = subObject.get("BankName").getAsString();//	银行名称
                    Name = subObject.get("Name").getAsString();//	姓名
                    BankAccount = subObject.get("BankAccount").getAsString();//	银行卡号
                }
            } else {
                message = object.get("message").getAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (status == 0) {
            String id = String.valueOf(user.getId());
            int i = bankCardService.deleteBankCardById(id);
            if (i > 0) {
                System.out.println("解绑银行卡成功！");
                view.setViewName("/user/txyhk");
            } else {
                System.out.println("解绑银行卡失败！");
                view.setViewName("/error/404");
            }
        } else {
            System.out.println("【逸富】解绑银行卡失败！");
            view.setViewName("/error/404");
        }
        return view;
    }

    @RequestMapping("/insertBankCard")
    public ModelAndView insertBankCard() {
        ModelAndView view = new ModelAndView();
        String time = String.valueOf(new Date().getTime());
        Integer status = null;
        String message = null;
        String BankName = null;

        Map<String, String> map = new LinkedHashMap<String, String>();
        String str = MD5Util.MD5_aa(time, "1.0");
        map.put("TimeStamp", time);
        map.put("Version", "1.0");
        map.put("SignMsg", str);

        String query = MapToStringSplicing.createLinkStringByGet(map);

        String result = null;
        try {
            result = HttpClientUtil.getProcessDefinitionList("http://120.55.162.84:8050/api/banks?" + query, map);
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result);
            JsonArray array = null;
            JsonObject subObject = null;
            status = object.get("status").getAsInt();
            if (status == 0) {
                array = object.get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    subObject = array.get(i).getAsJsonObject();
                    BankName = subObject.get("Name").getAsString();//	银行名称
                    int j = bankCardService.insertBankCard(BankName);
                    System.out.println(j);
                }
            } else {
                message = object.get("message").getAsString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            response.sendRedirect("/user/index");
        } catch (IOException e) {
            e.printStackTrace();
        }
        view.setViewName("/error/404");
        return view;
    }

    @RequestMapping("/selectBankCard")
    public ModelAndView selectBankCard() {
        ModelAndView view = new ModelAndView();
        Banks banks = bankCardService.selectBankCard();
        view.getModel().put("banks", banks);
        view.setViewName("/user/bdyhk");
        return view;
    }

    @RequestMapping("/selectBankCardById")
    public ModelAndView selectBankCardById() {
        ModelAndView view = new ModelAndView();
        User user = getUser(request);
        String id = String.valueOf(user.getId());
        bangding_banks bangdingBanks = bankCardService.selectBankCardById(id);
        if (bangdingBanks == null) {
            view.setViewName("user/txyhk");
        } else {
            String str = bangdingBanks.getBankAccount().replace(" ", "").substring(bangdingBanks.getBankAccount().replace(" ", "").length() - 4, bangdingBanks.getBankAccount().replace(" ", "").length());
            view.getModel().put("str", str);
            view.getModel().put("bangdingBanks", bangdingBanks);
            view.setViewName("user/unbund");
        }
        return view;
    }

}
